package com.hnpolice.luoxiaoke.sharetest;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ogaclejapan.rx.binding.Rx;
import com.ogaclejapan.rx.binding.RxProperty;
import com.ogaclejapan.rx.binding.RxView;

public class RXBingActivity extends AppCompatActivity {

	private Button mBtn;
	private TextView mTv;
	private SharedPreferences mSP;
	// //属性对象，封装了要观察的数据
	private RxProperty<String> spContent =RxProperty.create();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_rxbing);

		mBtn = (Button) findViewById(R.id.btn);
		mTv = (TextView) findViewById(R.id.tv1);
		mSP = this.getSharedPreferences("my_sharedpreference", MODE_PRIVATE);


		mSP.registerOnSharedPreferenceChangeListener(spListener);
		mSP.edit().putString("key", "我是原值").apply();
		mSP.edit().putString("key1", "我是原值1").apply();

		mBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mSP.edit().putString("key", "我是改后的值").apply();
				mSP.edit().putString("key1", "我是改后的值1").apply();
			}
		});


		//使用RxView将需要绑定的View对象和属性对象进行绑定，当属性对象的内容（被观察者）发生变化
		RxView.of(mTv).bind(spContent, new Rx.Action<TextView, String>() {
			@Override
			public void call(TextView target, String s) {
				target.setText(s);
				System.out.println("itchen--被观察到了------------>");
			}
		});


	}

	private SharedPreferences.OnSharedPreferenceChangeListener spListener = new SharedPreferences.OnSharedPreferenceChangeListener(){


		@Override
		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

			//这里只有一个功能,观察者的内容是从这里取
			//spContent.set(sharedPreferences.getString(key, ""));
			if (TextUtils.equals(key,"key")){
				spContent.set(sharedPreferences.getString("key", ""));//这个可以单独取出任何一个的值
			}

		}
	};


	@Override
	public void finish() {
		super.finish();

		mSP.unregisterOnSharedPreferenceChangeListener(spListener);
	}
}
